package com.example.data.permission.mp.redis;

import com.example.data.permission.entity.pojo.ShopDTO;
import com.example.data.permission.entity.pojo.UserInfoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.example.data.permission.mp.redis.LoginWithStorePermission.REDIS_PREFIX;

/**
 * Created by TD on 2021/7/22
 */

@Component
public class AuthUtil {

    private static  RedisTemplate<String, UserInfoDTO> redisTemplate;

    private static   BsdShopMapper bsdShopMapper;;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, UserInfoDTO> redisTemplate) {
        AuthUtil.redisTemplate = redisTemplate;
    }

    public static RedisTemplate<String, UserInfoDTO> getRedisTemplate() {
        return redisTemplate;
    }

    @Autowired
    public void setBsdShopMapper(BsdShopMapper bsdShopMapper) {
        AuthUtil.bsdShopMapper = bsdShopMapper;
    }
     ;

    // 根据用户名缓存查询用户信息
    public static UserInfoDTO getUserUserByName(String username) {
        return redisTemplate.opsForValue().get(REDIS_PREFIX + username);
    }

    // 根据门店ID 查询门店及下属所有信息
    public static List<Long> getShopsById(Long shopId) {
        List<Long> shops = new ArrayList<>();
        ShopDTO shopDTO = bsdShopMapper.getShopById(shopId);
        return getShopIdList(shopDTO, shops);
    }

    /**
     *  递归查询当前门店及下属门店所有ID
     */
    public static List<Long> getShopIdList(ShopDTO shopDTO, List<Long> shops) {
        if (shopDTO != null) {
            shops.add(shopDTO.getId());
            List<ShopDTO> children = shopDTO.getChildren();
            if (children.size() > 0) {
                children.forEach(e->{
                    getShopIdList(e,shops);
                });
            }
        }
        return shops;
    }
}
